<?php

namespace app\admin\controller;
use app\common\model\Topics;
class TopicsController extends BaseController{
  public function _initialize(){
    parent::_initialize();
    $this->Model = new Topics();
  }

  public function index(){
    $param = [];
    $param = $this->request->param();
    $res = $this->Model->managerSelect($param);
    $this->assign("param", $param);
    $this->assign("res", $res);
    return $this->fetch();
  }

  public function create(){
    if($this->request->isPost()){
      $data = $this->getPostData();
      $res = $this->Model->createOrUpdate($data);
      if($res["status"]){
        $this->success($res["msg"], 'index');
      }else{
        $this->error($res["msg"]);
      }
    }else{
      $this->assign("topics", ["status" => true, "wap_cover_id" => 0, "pc_cover_id" => 0]);
      return $this->fetch("form");
    }
  }

  /**
   * 显示指定的资源
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function read($id){
    
  }

  /**
   * 显示编辑资源表单页.
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function edit($id){
    $topics = $this->Model->where("id", $id)->find();
    if(empty($topics)){
      $this->redirect('index');
    }

    if($this->request->isPost()){
      $data = $this->getPostData();
      $res = $this->Model->createOrUpdate($data);
      if($res["status"]){
        $this->success($res["msg"], 'index');
      }else{
        $this->error($res["msg"]);
      }
    }else{
      $this->assign("topics", $topics);
      return $this->fetch("form");
    }
  }

  /**
   * 删除指定资源
   *
   * @param  int  $id
   * @return \think\Response
   */
  public function delete(){
    if($this->request->isDelete()){
      $id = $this->request->param("id");
      Article::destroy($id);
      $this->success("删除成功", url("index"));  
    }else{
      $this->error("您请求的方法不存在", url("index"));
    }
  }

  private function getPostData(){
    $atl_name = $this->request->action();
    $data = [];
    $param_name = ["id", "name", "title", "seo_title", "seo_keywords", "seo_description", "description", "content", "pc_cover_id", "wap_cover_id", "status"];
    $param = $this->request->post();
    foreach ($param_name as $key) {
      if(isset($param[$key])){
        $val = $param[$key];
      }else{
        $val = "";
      }

      if($key == "id" && empty($val)){
        continue;
      }

      switch ($key) {
      case "sort_num":
        $val = intval($val);
        break;
      case "status":
        if(empty($val)){
          $val = 0;
        }else{
          $val = 1;
        }
        break;
      default:
        $val = trim($val);  
      }
      $data[$key] = $val;
    }
    return $data;
  }
}
